<?php

header('Content-type: text/plain');

require_once('frontstart.inc.php');

class Application {
    function handle_request ($options) {
        try {
            if (! isset($_REQUEST['database'])) throw new \Exception('ERROR: the "database" parameter must be supplied');
            $database  = $_REQUEST['database'];
            if (! preg_match('/^[a-zA-Z0-9_]+$/', $database)) throw new \Exception('ERROR: the "database" parameter contains illegal characters (must be letters, digits, and underscores)');

            $schema  = (isset($_REQUEST['schema'])) ? $_REQUEST['schema'] : null;
            if ($schema && ! preg_match('/^[a-zA-Z0-9_]+$/', $schema)) throw new \Exception('ERROR: the "schema" parameter contains illegal characters (must be letters, digits, and underscores)');

            $table  = (isset($_REQUEST['table'])) ? $_REQUEST['table'] : null;
            if ($table && ! preg_match('/^[a-zA-Z0-9_]+$/', $table)) throw new \Exception('ERROR: the "table" parameter contains illegal characters (must be letters, digits, and underscores)');

            $force  = (isset($_REQUEST['force'])) ? $_REQUEST['force'] : 1;
            if ($force && ! preg_match('/^[01]$/', $force)) throw new \Exception('ERROR: the "force" parameter contains illegal characters (must be 0 or 1)');

            global $debug_sql, $trace;
            $debug_sql  = (isset($_REQUEST['debug_sql'])) ? $_REQUEST['debug_sql'] : 0;
            if ($debug_sql && ! preg_match('/^[012]$/', $debug_sql)) throw new \Exception('ERROR: the "debug_sql" parameter contains illegal characters (must be 0, 1, 2)');
            $trace  = (isset($_REQUEST['trace'])) ? $_REQUEST['trace'] : 0;
            if ($trace && ! preg_match('/^[01]$/', $trace)) throw new \Exception('ERROR: the "trace" parameter contains illegal characters (must be 0, 1)');

            $verbose = 1;

            $context = App::context($options);
            $db = $context->database($database);

            echo "initializing database [$database] metadata ...\n";
            $db->init_table_defs($schema, $table, $force, $verbose);
            echo "initialization of [$database] metadata complete.\n";
        }
        catch (Exception $e) {
            echo 'Failed: ', $e->getMessage(), '\n';
        }
    }
}

$application = new Application();
$application->handle_request($options);

